'use strict';

/**
 * @ngdoc service
 * @name webApp.httpIntercept
 * @description
 * # httpIntercept
 * Factory in the webApp.
 */
angular.module('webApp')
  .factory('httpIntercept', function ($rootScope,$q,cookie) {
    //登录安全锁
    var key = true;
    var intercept = {
      'request': function(config){
        if(cookie.getCookie('access_token')){
          config.headers.Authorization = cookie.getCookie('access_token');
        }
        if(config.url == '/v2/oauth/access-token' && key == false){
          config.url = '/404.html';
          alert('登录请求已发送请请5秒后再点击登录！');
        }
        else if(config.url == '/v2/oauth/access-token'){
          key = false;
          setTimeout(function(){
            key = true;
          },5000);
        }
        return $q.when(config);
      },
      'response': function(config){
        return $q.when(config);
      },
      'requestError': function(rejection){
        return $q.reject(rejection);
      },
      'responseError': function(rejection){
        //拦截不等于200所有错误
        if(rejection.status != 200 && rejection.status != 500 && rejection.status != 404 && rejection.status != 401){
          $rootScope.$broadcast('rejection',rejection);
        }
        else if(rejection.status == 404){
          $rootScope.$broadcast('rejection','远程服务器无法访问！');
        }
        else if(rejection.status == 500){
          alert('网络问题！');
        }
        else if(rejection.status == 401){
          $rootScope.$broadcast('401','');
        }
        return $q.reject(rejection);
      }
    };
    return intercept;
  });
